/*
 * @Author: lande 615542329@qq.com
 * @Date: 2023-02-23 11:18:51
 * @LastEditors: lande 615542329@qq.com
 * @LastEditTime: 2023-03-10 14:14:52
 * @FilePath: \GitStorage\Whatsapp_Project\whatsapp_register.js
 * @Description: register code
 * @version: 1.0.0
*/

// const Diy = require("/sdcard/code/diy_module.js");
const Diy = require("../Cloud_Control/diy_module");

const { clickWidget,
    clickWidgetEx,
    widgetBounds,
    findWidget,
    sleepEx,
    sml_move,
    smlMoveUp,
    getLevel,
    clearApp,
    closeApp,
    changeVpn,
    contactParam,
    ClassRequest,
    countryNameAll,
    PhoneParam
} = Diy;
const storage = storages.create("biyun");

try {
    const WSTaskParam = JSON.parse(storage.get("wsMsg", null));
    Console.log("WSTaskParam: ", WSTaskParam);
} catch (error) {
    console.log("获取ws推送数据报错: ", error);
}

const ClassRequestObj = new ClassRequest("192.168.80.33:80", "ddd5d6c783e943488f71", WSTaskParam.data.detailId);

function mainRegister(classObj) {
    this.status = null;
    try {
        if (typeof classObj != "object") {
            console.log("错误-传入的对象错误");
            this.status = "finish";
        } else {
            this.status = "launch";
        }
    } catch (error) {
        console.log("传入对象报错: ", error);
    }

    this.next = false;
    this.phoneNumber = classObj.phoneNumber;
    this.detailId = classObj.detailId;
    this.country = classObj.country;
    this.businessName = classObj.businessName;
    this.control = true;
    this.getPicStatus = false;
    this.taskStatus = false;

    /**
     * @description: 更改手机参数
     * @param {*} jsonParam
     * @return {*}
     */    
    this.changePhoenNum =function(jsonParam){
        const PhoneParamObj = new PhoneParam();      
        PhoneParamObj.main(jsonParam);
    }

    /**
     * @description: 启动WhatsApp
     * @return {*}
     */
    this.launch = function () {
        $app.launch("com.whatsapp.w4b");
        sleepEx(2000);
        let time1 = new Date().getTime();
        while (!findWidget({ text: "AGREE AND CONTINUE", id: "com.whatsapp.w4b:id/eula_accept", className: "android.widget.Button" }, "tic")) {
            clickWidget(findWidget({ text: "OK", id: "android:id/button2", className: "android.widget.Button" }, "tic"));
            let time2 = new Date().getTime();
            let time3 = parseInt(time2 - time1) / 1000;
            if (time3 > 15) {
                $app.launch("com.whatsapp.w4b");
                sleepEx(2000);
                time1 = new Date().getTime();
            }
            sleep(500);
        }
        this.status = "registerProcess";

    }
    
    /**
     * @description: 注册进程
     * @return {*}
     */
    this.registerProcess = function () {
        clickWidget(findWidget({ text: "AGREE AND CONTINUE", id: "com.whatsapp.w4b:id/eula_accept", className: "android.widget.Button" }, "tic"));
        if (findWidget({ text: "Verify your phone number", id: "com.whatsapp.w4b:id/register_phone_toolbar_title", className: "android.widget.TextView" })) {
            let widgetCountry = findWidget({ text: "Choose a country", id: "com.whatsapp.w4b:id/registration_country", className: "android.widget.TextView" }, "tic");
            if (widgetCountry && !(widgetCountry.text() === WSTaskParam.data.countryName)) {
                // 执行选择国家
                clickWidget(widgetCountry);
                sleepEx(1000);
                clickWidget(findWidget({ id: "com.whatsapp.w4b:id/menuitem_search", className: "android.widget.TextView" }, "ic"));
                sleepEx(1000);
                let widgetEdit = findWidget({ text: "Search countries", id: "com.whatsapp.w4b:id/search_src_text", className: "android.widget.EditText" }, "tic");
                if (widgetEdit) {
                    widgetEdit.setText(this.country);
                    sleepEx(1000);
                }
                this.next = clickWidget(findWidget({ text: countryNameAll(this.country), id: "com.whatsapp.w4b:id/country_first_name", className: "android.widget.TextView" }, "tic"));
            }

            let widgetPhoneEdit = findWidget({ text: "phone number", id: "com.whatsapp.w4b:id/registration_phone", className: "android.widget.EditText" }, "tic");
            if (widgetPhoneEdit) {
                widgetPhoneEdit.setText(this.phoneNumber);
                sleepEx(1000);
                if (this.next) {
                    clickWidget(findWidget({ text: "NEXT", id: "com.whatsapp.w4b:id/registration_submit", className: "android.widget.Button" }, "tic"));
                    console.log("完成-输入国家和手机号码下一步");
                }
            }
        }

        if (textStartsWith("You entered the phone number").id("android:id/message").className("android.widget.TextView").findOnce()) {
            this.clickButton1();
        }

        if (findWidget({ text: "We couldn't send an SMS to your number. Please check your number and try again in 1 hour.", id: "android:id/message" }, "ti")) {
            sleepEx(1000);
            this.clickButton1();
            this.status = "finish";
            return false;
        }
        if (textStartsWith("This phone number is currently registered with WhatsApp Messenger and can't be used in WhatsApp Business at the same time.").id("android:id/message").findOnce()) {
            clickWidget(findWidget({ text: "EDIT", id: "android:id/button3", className: "android.widget.Button" }, "tic"));
            sleepEx(1000);
            this.changePhoenNum(this.phoneNumber, this.detailId);
            sleepEx(1000);
            console.log("更换-手机号被使用过");
        }

        if (textStartsWith("You entered the phone number").id("android:id/message").className("android.widget.TextView").findOnce()) {
            this.clickButton1();
        }

        let widgetInput = findWidget({ id: "com.whatsapp.w4b:id/verify_sms_code_input", className: "android.widget.EditText" }, "ic");
        if (widgetInput) {
            let opt = ClassRequestObj.getOpt(this.phoneNumber, 120);
            if (opt.length > 0) {
                widgetInput.setText(opt);
                sleepEx(3000);
                console.log("成功-设置手机验证码");
                ClassRequestObj.changePhoenNum();
                console.log("释放手机号");
            } else {
                console.log("失败-获取手机验证码");
                this.status = "finish";
            }


        }
        if (findWidget({ text: "Create your business profile", id: "com.whatsapp.w4b:id/title", className: "android.widget.TextView" }, "tic")) {
            this.status = "setImage";
        }
    }


    // 设置头像
    this.setImage = function () {
        if (!this.getPicStatus) {
            // 获取图片
            let pathPic = "/sdcard/1.png";
            this.getPicStatus = true;
            media.scanFile(pathPic);
            console.log("成功-获取图片");
        }
        clickWidget(findWidget({ id: "com.whatsapp.w4b:id/change_photo_btn", className: "android.widget.ImageView" }, "ic")) ? sleepEx(500) : null;
        clickWidget(findWidget({ text: "Gallery", id: "com.whatsapp.w4b:id/name", className: "android.widget.TextView" }, "tic")) ? sleepEx(500) : null;
        clickWidget(findWidget({ text: "RECENTS", className: "android.widget.TextView" }, "tc")) ? sleepEx(500) : null;
        clickWidget(findWidget({ text: "Photo", className: "android.widget.ImageView" }, "tc")) ? sleepEx(500) : null;
        clickWidget(findWidget({ text: "DONE", id: "com.whatsapp.w4b:id/ok_btn", className: "android.widget.Button" }, "tic")) ? sleepEx(500) : null;
        if (findWidget({ text: "This photo is too small. Please select a photo with height and width of at least 192 pixels.", id: "android:id/message", className: "android.widget.TextView" }, "tic")) {
            this.clickButton1();
            this.getPicStatus = false;
            console.log("弹窗-图片尺寸太小");
        }
        if (findWidget({ text: "Create your business profile", id: "com.whatsapp.w4b:id/title", className: "android.widget.TextView" }, "tic")) {
            this.status = "setName";
        }
    }

    // 设置名字
    this.setName = function () {
        let inputEditText = findWidget({ id: "com.whatsapp.w4b:id/registration_name", className: "android.widget.EditText" }, "ic");
        if (inputEditText) {
            inputEditText.setText(this.businessName);
            sleepEx(500);
            console.log("完成-设置企业名字");
            this.status = "setCategory";
        }
    }

    // 设置企业类型
    this.setCategory = function () {
        clickWidget(findWidget({ text: "Category", id: "com.whatsapp.w4b:id/form_field_main_label", className: "android.widget.TextView" }, "tic"));
        let ArraySuggester = ["Other business",
            "Vehicle service",
            "Apparel & clothing",
            "Arts & entertainment",
            "Beauty, cosmetic & personal care",
            "Education",
            "Event planner",
            "Finance",
            "Supermarket/Convenience store"
        ];
        if (clickWidget(findWidget({ text: ArraySuggester[random(0, ArraySuggester.length - 1)], id: "com.whatsapp.w4b:id/category_listitem_text", className: "android.widget.TextView" }, "tic"))) {
            sleepEx(1000);
            if (clickWidget(findWidget({ text: "NEXT", id: "com.whatsapp.w4b:id/register_name_accept", className: "android.widget.Button" }, "tic"))) {
                sleepEx(1000);
                this.status = "toHome";
            }
        }
    }

    /**
     * @description: 进入到主页
     * @return {*}
     */
    this.toHome = function () {
        clickWidget(findWidget({ text: "NOT NOW", id: "com.whatsapp.w4b:id/onboarding_decline_button", className: "android.widget.Button" }, "tic"));
        if (findWidget({ text: "Chats", id: "com.whatsapp.w4b:id/tab", className: "android.widget.TextView" }, "tic")) {
            this.status = "finish";
        }
    }
    /**
     * @description: 点击ok按钮1
     * @return {*}
     */
    this.clickButton1 = function () {
        clickWidget(findWidget({ text: "OK", id: "android:id/button1", className: "android.widget.Button" }, "tic"));
    }
    /**
     * @description: main 主函数
     * @return {*}
     */
    this.main = function () {
        while (this.control) {
            switch (this.status) {
                case "launch":
                    this.launch();
                    break;
                case "registerProcess":
                    this.registerProcess();
                    break;
                case "setImage":
                    this.setImage();
                    break
                case "setName":
                    this.setName();
                    break;
                case "setCategory":
                    this.setCategory();
                    break;
                case "toHome":
                    this.toHome();
                    break;
                case "finish":
                    if (this.taskStatus) {
                        ClassRequestObj.finishTask(this.phoneNumber + " 注册成功!", 2);
                        console.log("成功-完成注册任务");
                    } else {
                        ClassRequestObj.finishTask(this.phoneNumber + " 注册失败!", 3);
                        console.log("失败-完成注册任务");
                    }

                    return;

            }

            sleep(100);
        }
    }

}

/**
 * @description: 
 * @return {*}
 */
function main() {
    let obj = {
        phoneNumber: WSTaskParam.data.phoneNumber,
        detalId: WSTaskParam.data.detailId,
        country: WSTaskParam.data.country,
        businessName: WSTaskParam.data.businessName
    }
    const mainRegisterObj = new mainRegister(obj);
    mainRegisterObj.main();

}